package com.wedimob.slideshare.task.cpu;

import org.jsoup.nodes.Document;

import com.wedimob.slideshare.WriteType;
import com.wedimob.slideshare.bo.SharedDocument;
import com.wedimob.slideshare.bo.Summary;
import com.wedimob.slideshare.parser.annotation.Factory;
import com.wedimob.slideshare.parser.strategy.ShareDocumentParser;
import com.wedimob.slideshare.parser.strategy.SlideShareDocumentParser;
import com.wedimob.slideshare.parser.strategy.YoutubeDocumentParser;
import com.wedimob.slideshare.source.SlideShareStrategy;
import com.wedimob.slideshare.source.YoutubeStrategy;
import com.wedimob.slideshare.task.PoolExecutor;
import com.wedimob.slideshare.task.Task;
import com.wedimob.slideshare.task.TaskType;
import com.wedimob.slideshare.task.disk.TaskDocumentWriter;

public class TaskDocumentExtractor extends Task<Document, SharedDocument> {

    private Summary summary;
    private WriteType write;

    public TaskDocumentExtractor(PoolExecutor pool, Summary summary,
            Document input, WriteType write, int timeout) {
        super(TaskType.CPU, pool, input, 0, timeout);
        this.write = write;
        if (summary != null)
            this.summary = summary;
        else
            this.summary = new Summary(Factory.buildURL(input, input.baseUri()));
    }

    @Override
    public void run() {
        try {

            ShareDocumentParser parser = null;

            if (accept(summary.getUrl(), SlideShareStrategy.URL_BASE)) {
                parser = new SlideShareDocumentParser(summary, input, write);                
            }

            if (accept(summary.getUrl(), YoutubeStrategy.URL_BASE)) {
                parser = new YoutubeDocumentParser(summary, input, write);                
            }
            
            if (parser == null) {
                throw new RuntimeException("Cannot handle " + summary.getUrl());
            }

            output = parser.get(pool, write, timeout);
            pool.getResults().putResult(output);

            if (write != WriteType.NONE) {
                pool.execAsync(new TaskDocumentWriter(pool, output, write, timeout));
            }

        } catch (Exception e) {
            e.printStackTrace();
            this.e = e;
        }
    }

}
